//
//  SearchResultProductViewController.m
//  BaseProject
//
//  Created by 王洋 on 2020/7/22.
//  Copyright © 2020 王洋. All rights reserved.
//
#import "ZZLayout.h"
#import "SearchNaviBarView.h"

#import "ProductListSortHeader.h"

#import "MarriageProductCell.h"
#import "ProductDetailViewController.h"


#import "SearchResultProductViewController.h"

@interface SearchResultProductViewController ()<UICollectionViewDelegate, UICollectionViewDataSource, ZZLayoutDelegate>

@property (nonatomic, strong) SearchNaviBarView *searchNavi;

@property (nonatomic, strong) ProductListSortHeader *sortHeader;

@property (nonatomic, strong) UICollectionView *collectionView;

@property (nonatomic, strong) NSMutableArray <CommonPackageModel *>*dataArray;

@property (nonatomic, assign) NSInteger pageNum;
@property (nonatomic, assign) NSInteger pageSize;

@property (nonatomic, assign) ProductListSortType type;

@end

@implementation SearchResultProductViewController


- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (instancetype)initWithKeyWord:(NSString *)keyWord {
    
    self = [super init];
    
    if (self) {
        self.keyWord = keyWord;
    }
    return self;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];

    [self initView];
    [self refreshParam];
    [self request_searchPackage];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(searchCallBack:) name:@"searchNoti" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginSuccessAction) name:@"BA_LoginSuccess" object:nil];
}

- (void)loginSuccessAction {
    [self.collectionView reloadData];
}

-(void)searchCallBack:(NSNotification *)Noti {
    
    self.keyWord = [Noti.userInfo objectForKey:@"keyWord"];
    [self refreshParam];
    [self request_searchPackage];
}

- (void)refreshParam {
    self.pageNum = 1;
    self.pageSize = 10;
}

- (void)initView {

    [self.view addSubview:self.sortHeader];
    [self.view addSubview:self.collectionView];
    
    [self.sortHeader mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.top.mas_equalTo(1);
        make.height.mas_equalTo(50);
    }];
    
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.top.mas_equalTo(self.sortHeader.mas_bottom);
        make.bottom.mas_equalTo(0);
    }];
    
    WEAKSELF
    self.sortHeader.ProductListSortHeaderBlock = ^(ProductListSortType type) {
      
        weakSelf.type = type;
        [weakSelf refreshParam];
        [weakSelf request_searchPackage];
        
    };
    
}

- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    
    CAGradientLayer *layer = [CAGradientLayer layer];
    layer.startPoint = CGPointMake(0, 0);
    layer.endPoint = CGPointMake(0, 1);
    
    layer.colors = @[(__bridge id)[[UIColor whiteColor] colorWithAlphaComponent:1].CGColor, (__bridge id)UIColorHex(0xf1f1f1).CGColor];
    
    layer.frame = CGRectMake(0, 0, TTScreenWidth, self.view.frame.size.height);
    [self.view.layer insertSublayer:layer atIndex:0];
}

#pragma mark- 协议方法
//collectionView的协议方法
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    return self.dataArray.count;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    
    UICollectionReusableView *reusableView = nil;
    // 区头
    if (kind == UICollectionElementKindSectionHeader) {
        UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"UICollectionElementKindSectionHeader" forIndexPath:indexPath];
        reusableView = headerView;
    }
    // 区尾
    if (kind == UICollectionElementKindSectionFooter) {
        UICollectionReusableView *footerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"UICollectionElementKindSectionFooter" forIndexPath:indexPath];
        reusableView = footerView;
    }
    return reusableView;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {

    ProductDetailViewController *vc = [[ProductDetailViewController alloc] init];
    vc.goodsId = self.dataArray[indexPath.row].goodsId;
    [self.navigationController pushViewController:vc animated:YES];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    MarriageProductCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MarriageProductCellID" forIndexPath:indexPath];
    [cell fillCellWithModel:self.dataArray[indexPath.row]];
    
    WEAKSELF
    cell.MarriageProductLoginBlock = ^{
      
        [weakSelf openLoginWithCompletion:^(BOOL isLogin, NSDictionary * _Nonnull options) {
            if (isLogin) {
                [weakSelf.collectionView reloadData];
            }
        }];
        
    };
    return cell;
}

//ZZLyout的流协议方法
- (CGFloat)layout:(ZZLayout *)layout heightForRowAtIndexPath:(NSIndexPath *)indexPath {//返回item的高

    return self.dataArray[indexPath.row].cellHeight;
}

- (NSInteger)layout:(ZZLayout *)layout columnNumberAtSection:(NSInteger)section {//每个区有几列

    return 2;
}

- (UIEdgeInsets)layout:(ZZLayout *)layout insetForSectionAtIndex:(NSInteger)section {//设置每个区的边距
    
    return UIEdgeInsetsMake(15, 15, 15, 15);
}

- (NSInteger)layout:(ZZLayout *)layout lineSpacingForSectionAtIndex:(NSInteger)section {//设置每个区的行间距

    return 10;
}

- (CGFloat)layout:(ZZLayout*)layout interitemSpacingForSectionAtIndex:(NSInteger)section {//设置每个区的列间距

    return 10;
}

- (CGSize)layout:(ZZLayout *)layout referenceSizeForHeaderInSection:(NSInteger)section {//设置区头的高度

    return CGSizeMake(TTScreenWidth, CGFLOAT_MIN);
}

- (CGSize)layout:(ZZLayout *)layout referenceSizeForFooterInSection:(NSInteger)section {//设置区尾的高度
    return CGSizeMake(TTScreenWidth, CGFLOAT_MIN);
}

- (CGFloat)layout:(ZZLayout*)layout spacingWithLastSectionForSectionAtIndex:(NSInteger)section {//本区区头和上个区区尾的间距
    return 0;
}

- (UIColor *)layout:(UICollectionView *)layout colorForSection:(NSInteger)section {//设置不同分区的不同背景颜色
    return [UIColor clearColor];
}

#pragma mark- 懒加载
- (UICollectionView *)collectionView {
    if (!_collectionView) {
        
        ZZLayout *layout = [[ZZLayout alloc] initWith:ZZLayoutFlowTypeVertical delegate:self];
        //打开区头悬浮功能(默认关闭)
        layout.sectionHeadersPinToVisibleBounds = NO;
        
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        _collectionView.backgroundColor = [UIColor clearColor];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        
        [_collectionView registerNib:[UINib nibWithNibName:@"MarriageProductCell" bundle:nil] forCellWithReuseIdentifier:@"MarriageProductCellID"];

        [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"UICollectionElementKindSectionHeader"];
        
        [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"UICollectionElementKindSectionFooter"];

        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.showsVerticalScrollIndicator = NO;

        _collectionView.bounces = YES;
        self.edgesForExtendedLayout = UIRectEdgeNone;
        if (@available(iOS 11.0, *)) {
            _collectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        
        WEAKSELF
        _collectionView.mj_header = [MJRefreshGifHeader headerWithRefreshingBlock:^{

            [weakSelf refreshParam];
            [weakSelf request_searchPackage];

        }];
//
        _collectionView.mj_footer = [MJRefreshBackGifFooter footerWithRefreshingBlock:^{
            weakSelf.pageNum++;
            [weakSelf request_searchPackage];
        }];
        
        
    }
    return _collectionView;
}

- (ProductListSortHeader *)sortHeader {
    
    if (!_sortHeader) {
        _sortHeader = [[NSBundle mainBundle] loadNibNamed:@"ProductListSortHeader"owner:nil options:nil].firstObject;
    }
    return _sortHeader;
}

- (NSMutableArray<CommonPackageModel *> *)dataArray {
    if (!_dataArray) {
        _dataArray = @[].mutableCopy;
    }
    return _dataArray;
}


- (void)request_searchPackage {
    
    NSMutableDictionary *dic = @{}.mutableCopy;

    [dic setValue:@(self.pageNum) forKey:@"pageNum"];
    [dic setValue:@(self.pageSize) forKey:@"pageSize"];
    
    NSDictionary *t = @{}.mutableCopy;

    //综合排序 1：综合 2：价格由高到低 3：价格由低到高  4热门
    [t setValue:@(self.type) forKey:@"comprehensive"];
    [t setValue:self.keyWord forKey:@"searchName"];
    [t setValue:@"4" forKey:@"type"];
    [t setValue:[TTUserModel sharedObject].cityId forKey:@"sellerCityId"];

    [dic setValue:t forKey:@"t"];

    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_SearchAll];
    
    WEAKSELF
    [SVProgressHUD showWithStatus:@"正在加载"];
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        
        [weakSelf.collectionView.mj_header endRefreshing];
        [weakSelf.collectionView.mj_footer endRefreshing];
        [[TTNoResultManager shareManager] hideNoResultWithView:weakSelf.collectionView];

        [SVProgressHUD dismiss];
        if ([data isKindOfClass:[NSDictionary class]]) {

            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {
                NSDictionary *resultDic = [data valueForKey:@"data"];
                
                if ([resultDic isKindOfClass:[NSDictionary class]]) {

                    NSArray *list = [resultDic valueForKey:@"list"];
                    
                    if (weakSelf.pageNum == 1) {
                        weakSelf.dataArray = @[].mutableCopy;
                        
                        if (list.count == 0) {
                            [[TTNoResultManager shareManager] showNoResultWithStateInView:weakSelf.collectionView errorCode:kTTViewState_NoSearchResult btnTitle:@"去问统筹师" didPressButton:^{
//                                你好，关于“搜索词”商家/套餐/案例/婚品，没有搜索到结果，我这边想咨询下
                                NSString *imStr = [NSString stringWithFormat:@"你好，关于“%@”婚品，没有搜索到结果，我这边想咨询下",self.keyWord];
                                [[TT_IMContactManager manager] ImContactWithType:TT_IMContactType_tongchoushi withQuickReply:imStr];
                            }];
                        }
                    }
                    
                    if ([list isKindOfClass:[NSArray class]]) {
                        for (int i = 0; i < list.count; i++) {
                            NSDictionary *listDic = list[i];
                            CommonPackageModel *productModel = [CommonPackageModel modelWithJSON:listDic];
                            productModel.cellHeight = [MarriageProductCell calculateHeightModel:productModel AndWidth:TTScreenWidth];
                            [weakSelf.dataArray addObject:productModel];
                        }
                    }

                    [weakSelf.collectionView reloadData];
                    
                }
            }
        }
        
    } FailedBlock:^(NSError * _Nonnull error) {
        
        [weakSelf.collectionView.mj_header endRefreshing];
        [weakSelf.collectionView.mj_footer endRefreshing];
        [SVProgressHUD dismiss];
    }];
    
}


@end
